//Tencent is pleased to support the open source community by making WeDemo available.
//Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
//Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
//http://opensource.org/licenses/MIT
//Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

#import "WXApiManager.h"
#import "RandomKey.h"
#import "CCLuaEngine.h"
#import "CCLuaStack.h"

static NSString* const kWXNotInstallErrorTitle = @"您还没有安装微信，不能使用微信分享功能";

@interface WXApiManager ()

@property (nonatomic, strong) NSString *authState;

@end

@implementation WXApiManager

#pragma mark - Life Cycle
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static WXApiManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initInPrivate];
    });
    return instance;
}

- (instancetype)initInPrivate {
    self = [super init];
    if (self) {
        _delegate = nil;
    }
    return self;
}

- (instancetype)init {
    return nil;
}

- (instancetype)copy {
    return nil;
}

#pragma mark - Public Methods
- (void)sendAuthRequestWithController:(UIViewController*)viewController
                             delegate:(id<WXAuthDelegate>)delegate {
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    
    self.authState = req.state = [NSString randomKey];
    self.delegate = delegate;
    
    bool ret = [WXApi sendAuthReq:req viewController:viewController delegate:self];
    
    //[req dealloc];
}

- (BOOL)sendLinkContent:(NSString *)urlString
                  Title:(NSString *)title
            Description:(NSString *)description
                AtScene:(enum WXScene)scene {
    
    if (![WXApi isWXAppInstalled]) {
        //ADShowErrorAlert(kWXNotInstallErrorTitle);
        return NO;
    }
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = urlString;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = description;
    message.mediaTagName = @"WECHAT_TAG_JUMP_SHOWRANK";
    message.mediaObject = ext;
    message.thumbData = UIImagePNGRepresentation([UIImage imageNamed:@"wxLogoGreen"]);

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.bText = NO;
    req.scene = scene;
    return [WXApi sendReq:req];
}

- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

/**
 *  等比缩放本图片大小
 *
 *  @param newImageWidth 缩放后图片宽度，像素为单位
 *
 *  @return self-->(image)
 */
- (UIImage *)scaleImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

- (BOOL)sendImageContent:(NSString *)imageName
                 Path:(NSString *)path
                 AtScene:(enum WXScene)scene {
    if (![WXApi isWXAppInstalled]) {
        //ADShowErrorAlert(kWXNotInstallErrorTitle);
        return NO;
    }
    
    //UIImageJPEGRepresentation(<#UIImage * _Nonnull image#>, 0.1);
    
    NSData* data = [NSData dataWithContentsOfFile:imageName];
    
    
    UIImage* image = [UIImage imageWithData: data];

    
    UIImage* imageSizeCompress = [self scaleImage:image newWidth:(CGFloat)320];

    //NSData* compressData = UIImageJPEGRepresentation(image, 0);
    
    UIImage* newImage = [self compressImage:imageSizeCompress toByte:30*1000];
    
    //compressData = UIImageJPEGRepresentation(newImage, 0);
    
    //newImage = [UIImage imageWithData:compressData ];
    
    WXMediaMessage *message = [WXMediaMessage message];
    [message setThumbImage:newImage];
    
    
    //
    WXImageObject* imageObject = [WXImageObject object];
    //NSString* filePath = [[NSBundle mainBundle] pathForResource:path ofType:@"jpg"];
    imageObject.imageData = [NSData dataWithContentsOfFile:imageName];
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.bText = NO;
    req.scene = scene;
    return [WXApi sendReq:req];
}

- (BOOL)sendFileData:(NSData *)fileData
       fileExtension:(NSString *)extension
               Title:(NSString *)title
         Description:(NSString *)description
          ThumbImage:(UIImage *)thumbImage
             AtScene:(enum WXScene)scene {
    if (![WXApi isWXAppInstalled]) {
        //ADShowErrorAlert(kWXNotInstallErrorTitle);
        return NO;
    }

    WXFileObject *ext = [WXFileObject object];
    ext.fileExtension = extension;
    ext.fileData = fileData;

    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = ext;
    message.title = title;
    message.description = description;
    [message setThumbImage:thumbImage];
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.bText = NO;
    req.scene = scene;
    
    return [WXApi sendReq:req];
}

#pragma mark - WXApiDelegate
-(void)onReq:(BaseReq*)req {
    // just leave it here, WeChat will not call our app
}

-(void)onResp:(BaseResp*)resp {    
    if([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp* authResp = (SendAuthResp*)resp;
        /* Prevent Cross Site Request Forgery */
        if (![authResp.state isEqualToString:self.authState]) {
            //if (self.delegate && [self.delegate respondsToSelector:@selector(wxAuthDenied)])
                //[self.delegate wxAuthDenied];
            cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
            cocos2d::LuaStack* luaStack = engine->getLuaStack();
            
            lua_getglobal(luaStack->getLuaState(), "Global_Login2WXResponse");
            luaStack->pushString( "");
            luaStack->executeFunction(1);
            return;
        }
        
        switch (resp.errCode) {
            case WXSuccess:
            {
                NSLog(@"RESP:code:%@,state:%@\n", authResp.code, authResp.state);
                NSString* code = ((SendAuthResp*)resp).code;
                cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
                cocos2d::LuaStack* luaStack = engine->getLuaStack();
                    
                lua_getglobal(luaStack->getLuaState(), "Global_Login2WXResponse");
                luaStack->pushString( [code cStringUsingEncoding:NSUTF8StringEncoding]);
                luaStack->executeFunction(1);
                break;
            }
            case WXErrCodeAuthDeny:
            case WXErrCodeUserCancel:
            default:
            {
                cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
                cocos2d::LuaStack* luaStack = engine->getLuaStack();
                    
                lua_getglobal(luaStack->getLuaState(), "Global_Login2WXResponse");
                luaStack->pushString( "");
                luaStack->executeFunction(1);
                break;
                }
        }
    }
    if([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp* sendMessageResp = (SendMessageToWXResp*)resp;
        cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
        cocos2d::LuaStack* luaStack = engine->getLuaStack();
        
        lua_getglobal(luaStack->getLuaState(), "Global_Share2WXResponse");
        luaStack->pushInt( (int)resp.errCode);
        luaStack->executeFunction(1);
    }
    
}


-(void)GetNetInfo{
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
    
    NSNumber *dataNetworkItemView = nil;
    NSNumber *signalStrengthItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
        }
        if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]]) {
            signalStrengthItemView = subview;
        }
        if (dataNetworkItemView && signalStrengthItemView) {
            break;
        }
    }
    
    if (!dataNetworkItemView) {
        //return nil;
    }
    
    NSNumber *networkTypeNum = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    NSNumber *wifiStrengthBars = [dataNetworkItemView valueForKey:@"wifiStrengthBars"];
    NSNumber *signalStrengthBars = [signalStrengthItemView valueForKey:@"signalStrengthBars"];
    if (!networkTypeNum) {
        //return nil;
    }
    NSString* str=nil;
    NSInteger networkType = [networkTypeNum integerValue];
    switch (networkType) {
        case 0:
            str=  @"";
            break;
            
        case 1:
            str=  [[NSString alloc] initWithFormat:@"%@,%@", @"2", signalStrengthBars];
            break;
            
        case 2:
            str=  [[NSString alloc] initWithFormat:@"%@,%@", @"2", signalStrengthBars];
            break;
            
        case 3:
            str=  [[NSString alloc] initWithFormat:@"%@,%@", @"2", signalStrengthBars];
            break;
            
        case 4:
            str=  [[NSString alloc] initWithFormat:@"%@,%@", @"2", signalStrengthBars];
            break;
            
        case 5:
            str=  [[NSString alloc] initWithFormat:@"%@,%@", @"1", wifiStrengthBars];
            break;
        default:
            str= [[NSString alloc] initWithFormat:@"%@,%@,%@", networkTypeNum, wifiStrengthBars, signalStrengthBars];
            break;
    }
    
    cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
    cocos2d::LuaStack* luaStack = engine->getLuaStack();
    lua_getglobal(luaStack->getLuaState(), "Global_Net");
    luaStack->pushString( [str UTF8String]);
    luaStack->executeFunction(1);
    
    [str dealloc];
}


- (void)GetPowerInfo
{
    NSNumber *batteryPercentage = nil;
    
    NSArray *statusBarSubviews = [[[[[UIApplication sharedApplication] valueForKey:@"_statusBar"] subviews] lastObject] subviews];
    
    for (id subview in statusBarSubviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarBatteryItemView")]) {
            batteryPercentage = [subview valueForKey:@"_capacity"];
            break;
        }
    }
    
    if(batteryPercentage == nil ) return;
    
    cocos2d::LuaEngine* engine = cocos2d::LuaEngine::getInstance();
    cocos2d::LuaStack* luaStack = engine->getLuaStack();
    lua_getglobal(luaStack->getLuaState(), "Global_Power");
    luaStack->pushInt( [batteryPercentage intValue]);
    luaStack->executeFunction(1);
}
@end
